package org.come.until;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileAesUtil {

    public static String key = "9123455789abccbd"; // AES加密时使用的密钥

    public static void encryptFile(String inputFile, String outputFile ) throws Exception {
        File inputFileObj = new File(inputFile);
        File outputFileObj = new File(outputFile);

        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        try (FileInputStream inputStream = new FileInputStream(inputFileObj);
             FileOutputStream outputStream = new FileOutputStream(outputFileObj)) {
            byte[] inputBytes = new byte[(int) inputFileObj.length()];
            inputStream.read(inputBytes);
            byte[] outputBytes = cipher.doFinal(inputBytes);
            outputStream.write(outputBytes);
        }
    }

    public static ByteArrayInputStream decryptFile(String inputFile) throws Exception {
        File inputFileObj = new File(inputFile);

        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        try (FileInputStream inputStream = new FileInputStream(inputFileObj)) {
            byte[] inputBytes = new byte[(int) inputFileObj.length()];
            inputStream.read(inputBytes);
            byte[] outputBytes = cipher.doFinal(inputBytes);
            return new ByteArrayInputStream(outputBytes);
        }
    }

    public static void main(String[] args) {
        String name = "xy_right";
        String inputFile = "resource/mouse/"+name+".tcp";
        String outputFile = "resource/mouse/"+name;
        try {
            encryptFile(inputFile, outputFile);
            //system.out.println("文件加密完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) throws Exception {
//        InputStream in = decryptFile("resource/mouse/xybj");
//
//    }

}
